package com.itheima.sky.service.impl;

import com.itheima.sky.dao.ShoppingCartMapper;
import com.itheima.sky.pojo.ShoppingCart;
import com.itheima.sky.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description ShoppingCartServiceImpl
 * @Author jiangning
 * @Date 2024-06-29
 */
@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Override
    public List<ShoppingCart> getCartByUserId(Long userId) {
        return shoppingCartMapper.getCartListByUserId(userId);
    }

    //根据用户id查找购物车列表
    @Override
    public List<ShoppingCart> getCartListByUserId(Long userId) {
        List<ShoppingCart> cartList=shoppingCartMapper.selectCartList(userId);
        return cartList;
    }

    //根据用户id新增购物车
    @Override
    public ShoppingCart addCartListByUserId(ShoppingCart shoppingCart) {
        log.info("新增购物车数据："+shoppingCart);
        //根据用户id判断当前这条数据是否存在于数据库中
        ShoppingCart shoppingCartOne=shoppingCartMapper.findExist(shoppingCart);
        //不存在就新增插入数据
        if(shoppingCartOne==null){
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insertCartList(shoppingCart);
            shoppingCartOne=shoppingCart;
        }else {
            //存在就数量+1
            shoppingCartOne.setNumber(shoppingCartOne.getNumber()+1);
            shoppingCartMapper.updateCartList(shoppingCartOne);
        }
        return shoppingCartOne;
    }

    //根据用户id删除购物车列表
    @Override
    public void cleanCartList(Long userId) {
        shoppingCartMapper.cleanCartList(userId);
    }

    //购物车商品数量减一
    @Override
    public void deleteCart(Long dishId){
        shoppingCartMapper.deleteCart(dishId);
    }

    //返回菜品数量
    @Override
    public Integer getNumber(Long setmeal_id) {
        return shoppingCartMapper.getNumber(setmeal_id);
    }

    /**
     * 获取购物车中菜的数量
     *
     * @param setmealId
     * @return
     */



    @Override
    public Integer getCount(Long setmealId, Long userId) {
        return shoppingCartMapper.getNumberBySetmealId(setmealId,userId);
    }

    /**
     * 根据用户清空购物车
     *
     * @param userId
     */
    @Override
    public void cleanUpCart(Long userId) {
        shoppingCartMapper.cleanUpCart(userId);
    }


    /**
     * 购物车减1
     *
     * @param setmealId
     */
    @Override
    public void subCart(Long setmealId, Long userId) {
        //判断当前setmealId的菜品数量是否为0，是的话调用删除方法，否则调用减一方法
        if(shoppingCartMapper.getNumberBySetmealId(setmealId,userId)==1){
            shoppingCartMapper.deleteCartOne(setmealId,userId);}
        else {
            shoppingCartMapper.declineCart(setmealId, userId);
        }
    }
}
